home *** CD-ROM | disk | FTP | other *** search
/ Clickx 63 / Clickx 63.iso / software / multimedia / mirov204 / Miro_Installer.exe / xulrunner / chrome / toolkit.jar / content / global / viewPartialSource.js < prev    next >
Encoding:
JavaScript  |  2008-04-22  |  16.5 KB  |  472 lines

  1. //@line 40 "/e/xr19rel/WINNT_5.2_Depend/mozilla/toolkit/components/viewsource/content/viewPartialSource.js"
  2.  
  3. var gDebug = 0;
  4. var gLineCount = 0;
  5. var gStartTargetLine = 0;
  6. var gEndTargetLine = 0;
  7. var gTargetNode = null;
  8.  
  9. var gEntityConverter = null;
  10. var gWrapLongLines = false;
  11. const gViewSourceCSS = 'resource://gre/res/viewsource.css';
  12. const NS_XHTML = 'http://www.w3.org/1999/xhtml';
  13.  
  14. // These are markers used to delimit the selection during processing. They
  15. // are removed from the final rendering, but we pick space-like characters for
  16. // safety (and futhermore, these are known to be mapped to a 0-length string
  17. // in transliterate.properties). It is okay to set start=end, we use findNext()
  18. // U+200B ZERO WIDTH SPACE
  19. const MARK_SELECTION_START = '\u200B\u200B\u200B\u200B\u200B';
  20. const MARK_SELECTION_END = '\u200B\u200B\u200B\u200B\u200B';
  21.  
  22. function onLoadViewPartialSource()
  23. {
  24.   // check the view_source.wrap_long_lines pref and set the menuitem's checked attribute accordingly
  25.   if (gPrefs) {
  26.     try {
  27.       var wraplonglinesPrefValue = gPrefs.getBoolPref('view_source.wrap_long_lines');
  28.       if (wraplonglinesPrefValue) {
  29.         document.getElementById('menu_wrapLongLines').setAttribute('checked', 'true');
  30.         gWrapLongLines = true;
  31.       }
  32.     } catch (e) { }
  33.     try {
  34.       document.getElementById("menu_highlightSyntax").setAttribute("checked", gPrefs.getBoolPref("view_source.syntax_highlight"));
  35.     } catch (e) {
  36.     }
  37.   } else {
  38.     document.getElementById("menu_highlightSyntax").setAttribute("hidden", "true");
  39.   }
  40.  
  41.   if (window.arguments[3] == 'selection')
  42.     viewPartialSourceForSelection(window.arguments[2]);
  43.   else
  44.     viewPartialSourceForFragment(window.arguments[2], window.arguments[3]);
  45.  
  46.   window._content.focus();
  47. }
  48.  
  49. ////////////////////////////////////////////////////////////////////////////////
  50. // view-source of a selection with the special effect of remapping the selection
  51. // to the underlying view-source output
  52. function viewPartialSourceForSelection(selection)
  53. {
  54.   var range = selection.getRangeAt(0);
  55.   var ancestorContainer = range.commonAncestorContainer;
  56.   var doc = ancestorContainer.ownerDocument;
  57.  
  58.   var startContainer = range.startContainer;
  59.   var endContainer = range.endContainer;
  60.   var startOffset = range.startOffset;
  61.   var endOffset = range.endOffset;
  62.  
  63.   // let the ancestor be an element
  64.   if (ancestorContainer.nodeType == Node.TEXT_NODE ||
  65.       ancestorContainer.nodeType == Node.CDATA_SECTION_NODE)
  66.     ancestorContainer = ancestorContainer.parentNode;
  67.  
  68.   // for selectAll, let's use the entire document, including <html>...</html>
  69.   // @see DocumentViewerImpl::SelectAll() for how selectAll is implemented
  70.   try {
  71.     if (ancestorContainer == doc.body)
  72.       ancestorContainer = doc.documentElement;
  73.   } catch (e) { }
  74.  
  75.   // each path is a "child sequence" (a.k.a. "tumbler") that
  76.   // descends from the ancestor down to the boundary point
  77.   var startPath = getPath(ancestorContainer, startContainer);
  78.   var endPath = getPath(ancestorContainer, endContainer);
  79.  
  80.   // clone the fragment of interest and reset everything to be relative to it
  81.   // note: it is with the clone that we operate/munge from now on
  82.   ancestorContainer = ancestorContainer.cloneNode(true);
  83.   startContainer = ancestorContainer;
  84.   endContainer = ancestorContainer;
  85.  
  86.   // Only bother with the selection if it can be remapped. Don't mess with
  87.   // leaf elements (such as <isindex>) that secretly use anynomous content
  88.   // for their display appearance.
  89.   var canDrawSelection = ancestorContainer.hasChildNodes();
  90.   if (canDrawSelection) {
  91.     var i;
  92.     for (i = startPath ? startPath.length-1 : -1; i >= 0; i--) {
  93.       startContainer = startContainer.childNodes.item(startPath[i]);
  94.     }
  95.     for (i = endPath ? endPath.length-1 : -1; i >= 0; i--) {
  96.       endContainer = endContainer.childNodes.item(endPath[i]);
  97.     }
  98.  
  99.     // add special markers to record the extent of the selection
  100.     // note: |startOffset| and |endOffset| are interpreted either as
  101.     // offsets in the text data or as child indices (see the Range spec)
  102.     // (here, munging the end point first to keep the start point safe...)
  103.     var tmpNode;
  104.     if (endContainer.nodeType == Node.TEXT_NODE ||
  105.         endContainer.nodeType == Node.CDATA_SECTION_NODE) {
  106.       // do some extra tweaks to try to avoid the view-source output to look like
  107.       // ...<tag>]... or ...]</tag>... (where ']' marks the end of the selection).
  108.       // To get a neat output, the idea here is to remap the end point from:
  109.       // 1. ...<tag>]...   to   ...]<tag>...
  110.       // 2. ...]</tag>...  to   ...</tag>]...
  111.       if ((endOffset > 0 && endOffset < endContainer.data.length) ||
  112.           !endContainer.parentNode || !endContainer.parentNode.parentNode)
  113.         endContainer.insertData(endOffset, MARK_SELECTION_END);
  114.       else {
  115.         tmpNode = doc.createTextNode(MARK_SELECTION_END);
  116.         endContainer = endContainer.parentNode;
  117.         if (endOffset == 0)
  118.           endContainer.parentNode.insertBefore(tmpNode, endContainer);
  119.         else
  120.           endContainer.parentNode.insertBefore(tmpNode, endContainer.nextSibling);
  121.       }
  122.     }
  123.     else {
  124.       tmpNode = doc.createTextNode(MARK_SELECTION_END);
  125.       endContainer.insertBefore(tmpNode, endContainer.childNodes.item(endOffset));
  126.     }
  127.  
  128.     if (startContainer.nodeType == Node.TEXT_NODE ||
  129.         startContainer.nodeType == Node.CDATA_SECTION_NODE) {
  130.       // do some extra tweaks to try to avoid the view-source output to look like
  131.       // ...<tag>[... or ...[</tag>... (where '[' marks the start of the selection).
  132.       // To get a neat output, the idea here is to remap the start point from:
  133.       // 1. ...<tag>[...   to   ...[<tag>...
  134.       // 2. ...[</tag>...  to   ...</tag>[...
  135.       if ((startOffset > 0 && startOffset < startContainer.data.length) ||
  136.           !startContainer.parentNode || !startContainer.parentNode.parentNode ||
  137.           startContainer != startContainer.parentNode.lastChild)
  138.         startContainer.insertData(startOffset, MARK_SELECTION_START);
  139.       else {
  140.         tmpNode = doc.createTextNode(MARK_SELECTION_START);
  141.         startContainer = startContainer.parentNode;
  142.         if (startOffset == 0)
  143.           startContainer.parentNode.insertBefore(tmpNode, startContainer);
  144.         else
  145.           startContainer.parentNode.insertBefore(tmpNode, startContainer.nextSibling);
  146.       }
  147.     }
  148.     else {
  149.       tmpNode = doc.createTextNode(MARK_SELECTION_START);
  150.       startContainer.insertBefore(tmpNode, startContainer.childNodes.item(startOffset));
  151.     }
  152.   }
  153.  
  154.   // now extract and display the syntax highlighted source
  155.   tmpNode = doc.createElementNS(NS_XHTML, 'div');
  156.   tmpNode.appendChild(ancestorContainer);
  157.  
  158.   // the load is aynchronous and so we will wait until the view-source DOM is done
  159.   // before drawing the selection.
  160.   if (canDrawSelection) {
  161.     window.document.getElementById("content").addEventListener("load", drawSelection, true);
  162.   }
  163.  
  164.   // all our content is held by the data:URI and URIs are internally stored as utf-8 (see nsIURI.idl)
  165.   var loadFlags = Components.interfaces.nsIWebNavigation.LOAD_FLAGS_NONE;
  166.   getBrowser().webNavigation
  167.               .loadURI("view-source:data:text/html;charset=utf-8," + encodeURIComponent(tmpNode.innerHTML),
  168.                        loadFlags, null, null, null);
  169. }
  170.  
  171. ////////////////////////////////////////////////////////////////////////////////
  172. // helper to get a path like FIXptr, but with an array instead of the "tumbler" notation
  173. // see FIXptr: http://lists.w3.org/Archives/Public/www-xml-linking-comments/2001AprJun/att-0074/01-NOTE-FIXptr-20010425.htm
  174. function getPath(ancestor, node)
  175. {
  176.   var n = node;
  177.   var p = n.parentNode;
  178.   if (n == ancestor || !p)
  179.     return null;
  180.   var path = new Array();
  181.   if (!path)
  182.     return null;
  183.   do {
  184.     for (var i = 0; i < p.childNodes.length; i++) {
  185.       if (p.childNodes.item(i) == n) {
  186.         path.push(i);
  187.         break;
  188.       }
  189.     }
  190.     n = p;
  191.     p = n.parentNode;
  192.   } while (n != ancestor && p);
  193.   return path;
  194. }
  195.  
  196. ////////////////////////////////////////////////////////////////////////////////
  197. // using special markers left in the serialized source, this helper makes the
  198. // underlying markup of the selected fragment to automatically appear as selected
  199. // on the inflated view-source DOM
  200. function drawSelection()
  201. {
  202.   getBrowser().contentDocument.title =
  203.     getViewSourceBundle().getString("viewSelectionSourceTitle");
  204.  
  205.   // find the special selection markers that we added earlier, and
  206.   // draw the selection between the two...
  207.   var findService = null;
  208.   try {
  209.     // get the find service which stores the global find state
  210.     findService = Components.classes["@mozilla.org/find/find_service;1"]
  211.                             .getService(Components.interfaces.nsIFindService);
  212.   } catch(e) { }
  213.   if (!findService)
  214.     return;
  215.  
  216.   // cache the current global find state
  217.   var matchCase     = findService.matchCase;
  218.   var entireWord    = findService.entireWord;
  219.   var wrapFind      = findService.wrapFind;
  220.   var findBackwards = findService.findBackwards;
  221.   var searchString  = findService.searchString;
  222.   var replaceString = findService.replaceString;
  223.  
  224.   // setup our find instance
  225.   var findInst = getBrowser().webBrowserFind;
  226.   findInst.matchCase = true;
  227.   findInst.entireWord = false;
  228.   findInst.wrapFind = true;
  229.   findInst.findBackwards = false;
  230.  
  231.   // ...lookup the start mark
  232.   findInst.searchString = MARK_SELECTION_START;
  233.   var startLength = MARK_SELECTION_START.length;
  234.   findInst.findNext();
  235.  
  236.   var contentWindow = getBrowser().contentDocument.defaultView;
  237.   var selection = contentWindow.getSelection();
  238.   var range = selection.getRangeAt(0);
  239.  
  240.   var startContainer = range.startContainer;
  241.   var startOffset = range.startOffset;
  242.  
  243.   // ...lookup the end mark
  244.   findInst.searchString = MARK_SELECTION_END;
  245.   var endLength = MARK_SELECTION_END.length;
  246.   findInst.findNext();
  247.  
  248.   var endContainer = selection.anchorNode;
  249.   var endOffset = selection.anchorOffset;
  250.  
  251.   // reset the selection that find has left
  252.   selection.removeAllRanges();
  253.  
  254.   // delete the special markers now...
  255.   endContainer.deleteData(endOffset, endLength);
  256.   startContainer.deleteData(startOffset, startLength);
  257.   if (startContainer == endContainer)
  258.     endOffset -= startLength; // has shrunk if on same text node...
  259.   range.setEnd(endContainer, endOffset);
  260.  
  261.   // show the selection and scroll it into view
  262.   selection.addRange(range);
  263.   // the default behavior of the selection is to scroll at the end of
  264.   // the selection, whereas in this situation, it is more user-friendly
  265.   // to scroll at the beginning. So we override the default behavior here
  266.   try {
  267.     getBrowser().docShell
  268.                 .QueryInterface(Components.interfaces.nsIInterfaceRequestor)
  269.                 .getInterface(Components.interfaces.nsISelectionDisplay)
  270.                 .QueryInterface(Components.interfaces.nsISelectionController)
  271.                 .scrollSelectionIntoView(Components.interfaces.nsISelectionController.SELECTION_NORMAL,
  272.                                          Components.interfaces.nsISelectionController.SELECTION_ANCHOR_REGION,
  273.                                          true);
  274.   }
  275.   catch(e) { }
  276.  
  277.   // restore the current find state
  278.   findService.matchCase     = matchCase;
  279.   findService.entireWord    = entireWord;
  280.   findService.wrapFind      = wrapFind;
  281.   findService.findBackwards = findBackwards;
  282.   findService.searchString  = searchString;
  283.   findService.replaceString = replaceString;
  284.  
  285.   findInst.matchCase     = matchCase;
  286.   findInst.entireWord    = entireWord;
  287.   findInst.wrapFind      = wrapFind;
  288.   findInst.findBackwards = findBackwards;
  289.   findInst.searchString  = searchString;
  290. }
  291.  
  292. ////////////////////////////////////////////////////////////////////////////////
  293. // special handler for markups such as MathML where reformatting the output is
  294. // helpful
  295. function viewPartialSourceForFragment(node, context)
  296. {
  297.   gTargetNode = node;
  298.   if (gTargetNode && gTargetNode.nodeType == Node.TEXT_NODE)
  299.     gTargetNode = gTargetNode.parentNode;
  300.  
  301.   // walk up the tree to the top-level element (e.g., <math>, <svg>)
  302.   var topTag;
  303.   if (context == 'mathml')
  304.     topTag = 'math';
  305.   else
  306.     throw 'not reached';
  307.   var topNode = gTargetNode;
  308.   while (topNode && topNode.localName != topTag)
  309.     topNode = topNode.parentNode;
  310.   if (!topNode)
  311.     return;
  312.  
  313.   // serialize
  314.   var title = getViewSourceBundle().getString("viewMathMLSourceTitle");
  315.   var wrapClass = gWrapLongLines ? ' class="wrap"' : '';
  316.   var source =
  317.     '<html>'
  318.   + '<head><title>' + title + '</title>'
  319.   + '<link rel="stylesheet" type="text/css" href="' + gViewSourceCSS + '">'
  320.   + '<style type="text/css">'
  321.   + '#target { border: dashed 1px; background-color: lightyellow; }'
  322.   + '</style>'
  323.   + '</head>'
  324.   + '<body id="viewsource"' + wrapClass
  325.   +        ' onload="document.title=\''+title+'\';document.getElementById(\'target\').scrollIntoView(true)">'
  326.   + '<pre>'
  327.   + getOuterMarkup(topNode, 0)
  328.   + '</pre></body></html>'
  329.   ; // end
  330.  
  331.   // display
  332.   var doc = getBrowser().contentDocument.wrappedJSObject;
  333.   doc.open("text/html", "replace");
  334.   doc.write(source);
  335.   doc.close();
  336. }
  337.  
  338. ////////////////////////////////////////////////////////////////////////////////
  339. function getInnerMarkup(node, indent) {
  340.   var str = '';
  341.   for (var i = 0; i < node.childNodes.length; i++) {
  342.     str += getOuterMarkup(node.childNodes.item(i), indent);
  343.   }
  344.   return str;
  345. }
  346.  
  347. ////////////////////////////////////////////////////////////////////////////////
  348. function getOuterMarkup(node, indent) {
  349.   var newline = '';
  350.   var padding = '';
  351.   var str = '';
  352.   if (node == gTargetNode) {
  353.     gStartTargetLine = gLineCount;
  354.     str += '</pre><pre id="target">';
  355.   }
  356.  
  357.   switch (node.nodeType) {
  358.   case Node.ELEMENT_NODE: // Element
  359.     // to avoid the wide gap problem, '\n' is not emitted on the first
  360.     // line and the lines before & after the <pre id="target">...</pre>
  361.     if (gLineCount > 0 &&
  362.         gLineCount != gStartTargetLine &&
  363.         gLineCount != gEndTargetLine) {
  364.       newline = '\n';
  365.     }
  366.     gLineCount++;
  367.     if (gDebug) {
  368.       newline += gLineCount;
  369.     }
  370.     for (var k = 0; k < indent; k++) {
  371.       padding += ' ';
  372.     }
  373.     str += newline + padding
  374.         +  '<<span class="start-tag">' + node.nodeName + '</span>';
  375.     for (var i = 0; i < node.attributes.length; i++) {
  376.       var attr = node.attributes.item(i);
  377.       if (!gDebug && attr.nodeName.match(/^[-_]moz/)) {
  378.         continue;
  379.       }
  380.       str += ' <span class="attribute-name">'
  381.           +  attr.nodeName
  382.           +  '</span>=<span class="attribute-value">"'
  383.           +  unicodeTOentity(attr.nodeValue)
  384.           +  '"</span>';
  385.     }
  386.     if (!node.hasChildNodes()) {
  387.       str += '/>';
  388.     }
  389.     else {
  390.       str += '>';
  391.       var oldLine = gLineCount;
  392.       str += getInnerMarkup(node, indent + 2);
  393.       if (oldLine == gLineCount) {
  394.         newline = '';
  395.         padding = '';
  396.       }
  397.       else {
  398.         newline = (gLineCount == gEndTargetLine) ? '' : '\n';
  399.         gLineCount++;
  400.         if (gDebug) {
  401.           newline += gLineCount;
  402.         }
  403.       }
  404.       str += newline + padding
  405.           +  '</<span class="end-tag">' + node.nodeName + '</span>>';
  406.     }
  407.     break;
  408.   case Node.TEXT_NODE: // Text
  409.     var tmp = node.nodeValue;
  410.     tmp = tmp.replace(/(\n|\r|\t)+/g, " ");
  411.     tmp = tmp.replace(/^ +/, "");
  412.     tmp = tmp.replace(/ +$/, "");
  413.     if (tmp.length != 0) {
  414.       str += '<span class="text">' + unicodeTOentity(tmp) + '</span>';
  415.     }
  416.     break;
  417.   default:
  418.     break;
  419.   }
  420.  
  421.   if (node == gTargetNode) {
  422.     gEndTargetLine = gLineCount;
  423.     str += '</pre><pre>';
  424.   }
  425.   return str;
  426. }
  427.  
  428. ////////////////////////////////////////////////////////////////////////////////
  429. function unicodeTOentity(text)
  430. {
  431.   const charTable = {
  432.     '&': '&<span class="entity">amp;</span>',
  433.     '<': '&<span class="entity">lt;</span>',
  434.     '>': '&<span class="entity">gt;</span>',
  435.     '"': '&<span class="entity">quot;</span>'
  436.   };
  437.  
  438.   function charTableLookup(letter) {
  439.     return charTable[letter];
  440.   }
  441.  
  442.   function convertEntity(letter) {
  443.     try {
  444.       var unichar = gEntityConverter.ConvertToEntity(letter, entityVersion);
  445.       var entity = unichar.substring(1); // extract '&'
  446.       return '&<span class="entity">' + entity + '</span>';
  447.     } catch (ex) {
  448.       return letter;
  449.     }
  450.   }
  451.  
  452.   if (!gEntityConverter) {
  453.     try {
  454.       gEntityConverter =
  455.         Components.classes["@mozilla.org/intl/entityconverter;1"]
  456.                   .createInstance(Components.interfaces.nsIEntityConverter);
  457.     } catch(e) { }
  458.   }
  459.  
  460.   const entityVersion = Components.interfaces.nsIEntityConverter.entityW3C;
  461.  
  462.   var str = text;
  463.  
  464.   // replace chars in our charTable
  465.   str = str.replace(/[<>&"]/g, charTableLookup);
  466.  
  467.   // replace chars > 0x7f via nsIEntityConverter
  468.   str = str.replace(/[^\0-\u007f]/g, convertEntity);
  469.  
  470.   return str;
  471. }
  472.